<template>
  <div class="login-container">
    <q-card class="login-card">
      <q-card-section>
        <div class="text-h6 text-center">用户登录</div>
      </q-card-section>

      <q-card-section>
        <q-form @submit="onSubmit" class="q-gutter-md">
          <q-input
            v-model="form.username"
            label="用户名/手机号"
            :rules="[
              val => !!val || '请输入用户名或手机号'
            ]"
          />

          <q-input
            v-model="form.password"
            label="密码"
            type="password"
            :rules="[
              val => !!val || '请输入密码'
            ]"
          />

          <div class="row justify-between items-center">
            <q-btn
              flat
              label="去注册"
              color="primary"
              @click="$router.push('/register')"
            />
            <q-btn
              type="submit"
              label="登录"
              color="primary"
              :loading="loading"
            />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import { useUserStore } from '../stores/user';

const router = useRouter();
const $q = useQuasar();
const userStore = useUserStore();

const loading = ref(false);
const form = reactive({
  username: '',
  password: ''
});

const onSubmit = async () => {
  try {
    loading.value = true;
    // 判断输入的是用户名还是手机号
    const isPhone = /^1[3-9]\d{9}$/.test(form.username);
    const loginData: { password: string; username?: string; phone?: string } = {
      password: form.password
    };
    
    if (isPhone) {
      loginData.phone = form.username;
    } else {
      loginData.username = form.username;
    }

    const userData = await userStore.login(loginData);
    // 只保存用户信息到 localStorage，token由userStore管理
    localStorage.setItem('user', JSON.stringify(userData));
    
    $q.notify({
      message: '登录成功',
      color: 'positive'
    });
    router.push('/');
  } catch (error: any) {
    $q.notify({
      message: error.message || '登录失败',
      color: 'negative'
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  position: fixed;
  top: 0;
  left: 0;
}

.login-card {
  width: 100%;
  max-width: 400px;
  margin: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
</style> 